<?php
/**
 * Description: 模考课程报名
 * User: devforma
 * Date: 15/9/17
 * Time: 15:34
 */

class EnrollMockCourse implements iController {

    /**
     * api请求处理主函数
     * @param array $queryArgs 就是$_REQUEST变量
     * @return array api返回结果，必须含response_code
     */
    public function output($queryArgs) {
        global $cmsdb;

        if (validateUser($queryArgs) !== 1)
            return genOutput(1000);

        if (empty($queryArgs['course_id']) || !filter_var($queryArgs['course_id'], FILTER_VALIDATE_INT))
            return genOutput(1000);

        //验证课程有效性
        $course = $cmsdb->getRow('SELECT `id`, `price` FROM `data_live_course` WHERE `id`=:id',
            array(':id' => $queryArgs['course_id']));

        $price = floatval($course->price);
        if (empty($course) || !empty($price)) {
            return genOutput(1000);
        }

        //检查是否报过名
        $enrolled = $cmsdb->getRow('SELECT `id` FROM `relation_user_product` WHERE `user_id`=:uid AND `product_id`=:pid
        AND `product_type`="zhiboke"', array(':uid' => $queryArgs['user_id'], ':pid' => $queryArgs['course_id']));

        if ($enrolled) {
            return genOutput(1001);
        }

        //报名
        $cmsdb->insert('original_orders', array(
            'product_id' => $queryArgs['course_id'],
            'product_type' => 'zhiboke',
            'user_id' => $queryArgs['user_id'],
            'price' => $price,
            'count' => 1,
            'create_time' => date('Y-m-d H:i:s'),
            'client' => empty($queryArgs['terminal_type']) ? '' : $queryArgs['terminal_type'],
            'platform_order' => '',
            'success' => 1,
            'platform' => '',
            'invite_user_id' => 0,
            'has_express' => 0
        ));

        $cmsdb->insert('relation_user_product', array(
            'user_id' => $queryArgs['user_id'],
            'product_id' => $queryArgs['course_id'],
            'product_type' => 'zhiboke',
            'order_time' => date('y-m-d H:i:s'),
            'order_id' => $cmsdb->lastInsertId()
        ));

        updateCoursePurchasedPersons($queryArgs['course_id'], 1);

        return genOutput(1);
    }
}